package cn.edu.lingnan.fruitshop.service.impl;

import cn.edu.lingnan.fruitshop.common.JSONResult;
import cn.edu.lingnan.fruitshop.mapper.BrowseMapper;
import cn.edu.lingnan.fruitshop.mapper.GoodstableMapper;
import cn.edu.lingnan.fruitshop.pojo.Address;
import cn.edu.lingnan.fruitshop.mapper.AddressMapper;
import cn.edu.lingnan.fruitshop.pojo.Browse;
import cn.edu.lingnan.fruitshop.pojo.Goodstable;
import cn.edu.lingnan.fruitshop.pojo.User;
import cn.edu.lingnan.fruitshop.service.AddressService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张小凡
 * @since 2022-01-04
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Autowired(required = false)
    private AddressMapper addressMapper;
    @Autowired(required = false)
    private BrowseMapper browseMapper;
    @Resource
    private GoodstableMapper goodstableMapper;

    /**
     * 跳转到商家个人信息界面
     * @param model
     * @param session
     * @return
     */
    @Override
    public String toSellerCenterInfo(Model model, HttpSession session) {
//        获取商家用户id
        User user =(User) session.getAttribute("user");
//        查询该id的address信息
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        Address sellerInfo = addressMapper.selectOne(queryWrapper);
//        判断address是否为空
        if(sellerInfo==null){
//            如果找不到address信息，返回一个设定信息
            model.addAttribute("sellerInfo",new Address().setUserName("<未填写>").setPhone("<未填写>").setAddress("<未填写>"));
        }else {
//            将address信息绑定到商家页面
            model.addAttribute("sellerInfo",sellerInfo);
        }
        return "user/seller_center_info";
    }

    /**
     * 商户更改自己的address信息
     * @param address
     * @param session
     * @return
     */
    @Override
    public JSONResult<Void> sellerUpdateAddressInfo(Address address,HttpSession session) {
//        拿到个人信息
        User user = (User) session.getAttribute("user");
//        根据user_id确认修改列
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",address.getId());
        Address address1 = addressMapper.selectOne(queryWrapper);
        if(address1==null){
//            如果没有个人address信息，就把userid加上之后执行插入语句
            address.setUserId(user.getUserId());
            address.setFlag(1);
            addressMapper.insert(address);
            return new JSONResult<>(200,"修改成功！！！");
        }
//        根据id修改个人信息
        addressMapper.update(address,queryWrapper);
        return new JSONResult<>(200,"修改成功！！！");
    }

    /**
     * 跳转到用户个人信息界面
     * @param model
     * @param session
     * @return
     */
    @Override
    public String toUserCenterInfo(Model model, HttpSession session) {
//        获取用户id
        User user =(User) session.getAttribute("user");
//        判断权限 0商家 1会员 2普通用户
//        if(user.getFlag()!=2){
//            return "";
//        }
//        查询该id的address信息
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId()).eq("flag",1);
        Address sellerInfo = addressMapper.selectOne(queryWrapper);
//        判断address是否为空
        if(sellerInfo==null){
//            如果找不到address信息，返回一个设定信息
            model.addAttribute("userInfo",new Address().setUserName("<未填写>").setPhone("<未填写>").setAddress("<未填写>"));
        }else {
//            将address信息绑定到个人信息页面
            model.addAttribute("userInfo",sellerInfo);
        }
//        查询该id的browse信息
        QueryWrapper<Browse> queryWrapper1 = new QueryWrapper<>();
//        根据时间降序排序
        queryWrapper1.eq("user_id",user.getUserId()).orderByDesc("search_time");
//        将浏览记录绑定到个人界面
        List<Browse> browses = browseMapper.selectList(queryWrapper1);

        model.addAttribute("browses",browses);
        if (browses==null){
//            如果没有浏览记录
            return "user/user_center_info";
        }else {
            QueryWrapper<Goodstable> queryWrapper2 = new QueryWrapper<>();
//            将食品表信息绑定到个人信息界面
            List<Goodstable> goodstables = goodstableMapper.selectList(queryWrapper2);
            model.addAttribute("goodstables",goodstables);
        }
        return "user/user_center_info";
    }

    /**
     * 跳转到用户收获地址界面
     * @param model
     * @param session
     * @return
     */
    @Override
    public String toUserCenterSite(Model model, HttpSession session) {
//        获取当前登录用户信息
        User user = (User) session.getAttribute("user");
//        根据用户id查找相应address数据
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        queryWrapper.orderByDesc("flag");
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        model.addAttribute("addresses",addresses);
        return "user/user_center_site";
    }

    @Override
    public String setDefault(Integer id,HttpSession session) {
//        拿到该用户id
        User user = (User) session.getAttribute("user");
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
//        根据id 将原默认值取消
        queryWrapper.eq("user_id",user.getUserId()).eq("flag",1);
        Address address = new Address().setFlag(0);
        addressMapper.update(address,queryWrapper);
//        将新选择设置为默认
        QueryWrapper<Address> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",id);
        address.setFlag(1);
        addressMapper.update(address,queryWrapper1);
        return "redirect:/toUserCenterSite";
    }

    /**
     * 增加收货地址-检查收货人名字
     * @param userName
     * @return
     */
    @Override
    public JSONResult<Void> checkAddressConsignee(String userName) {
        if("".equals(userName)||userName==null){
            return new JSONResult<>(201,"✗收货人不能为空");
        }
        return new JSONResult<>(200,"✓格式正确");
    }

    /**
     * 增加收货地址-检查收货地址
     * @param address
     * @return
     */
    @Override
    public JSONResult<Void> checkAddressAddress(String address) {
        if("".equals(address)||address==null){
            return new JSONResult<>(201,"✗收货地址不能为空");
        }
        return new JSONResult<>(200,"✓已输入");
    }

    /**
     * 增加收货地址-检查电话号码
     * @param phone
     * @return
     */
    @Override
    public JSONResult<Void> checkAddressPhone(String phone) {
        if("".equals(phone)||phone==null){
            return new JSONResult<>(201,"✗手机号码不能为空");
        }
        String regex = "^\\d{11}$";
        if (!phone.matches(regex)){
            return new JSONResult<>(202,"✗手机格式不正确");
        }
        return new JSONResult<>(200,"✓输入正确");
    }
    /**
     * 增加收货地址
     * @param address
     * @param session
     * @return
     */
    @Override
    public JSONResult<Void> addAddress(Address address, HttpSession session) {
//        判断收货人姓名是否为空
        JSONResult<Void> result1 = checkAddressConsignee(address.getUserName());
        if(result1.getCode()!=200){
            return result1;
        }
//        判断收货地址是否为空
        JSONResult<Void> result2 = checkAddressAddress(address.getAddress());
        if(result2.getCode()!=200){
            return result2;
        }
//        判断电话是否为空且格式是否正确
        JSONResult<Void> result3 = checkAddressPhone(address.getPhone());
        if(result3.getCode()!=200){
            return result3;
        }
//        插入address表
        User user = (User) session.getAttribute("user");
//        if(user==null){
//            return new JSONResult<>(204,"用户会话超时，请重新登录");
//        }
        address.setUserId(user.getUserId());
//        判断该用户有没有address信息 没有 flag设置为 默认1 有设置为0
        address.setFlag(0);
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        if (addressMapper.selectList(queryWrapper).size()==0){
            address.setFlag(1);
        }
        addressMapper.insert(address);
        return new JSONResult<>(200,"添加收货地址成功");
    }

    @Override
    public String deleteAdmin(Integer id) {
//        拿到删除列信息
        Address address = addressMapper.selectById(id);
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
//        拿该账户的地址信息flag为0的信息
        queryWrapper.eq("user_id",address.getUserId()).eq("flag",0);
        List<Address> addresses = addressMapper.selectList(queryWrapper);
//        如果该账户的地址信息flag为0的信息存在
        if(addresses.size()!=0){
//            拿第一个地址信息设置为flag 为1
            addressMapper.updateById(addresses.get(0).setFlag(1));
        }
//        执行删除
        addressMapper.deleteById(id);
        return "redirect:/toUserCenterAdmin";
    }

    @Override
    public String updateAdmin(Address address) {
        addressMapper.updateById(address);
        return "redirect:/toUserCenterAdmin";
    }

    //    跳转用户地址管理界面
    @Override
    public String toUserCenterAdmin(Model model, HttpSession session) {
//        获取当前登录用户信息
        User user = (User) session.getAttribute("user");
//        根据用户id查找相应address数据
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id",user.getUserId());
        queryWrapper.eq("user_id",1);//测试：先把userId写死
        queryWrapper.orderByDesc("flag");
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        model.addAttribute("addresses",addresses);
        return "user/user_center_admin";
    }
}
